package filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.protocol.RequestContent;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

@Component
public class ZuulTestFilter extends ZuulFilter {

    //返回zuul过滤器类型 "pre""route" "post""error"
    public String filterType() {
        return "pre";
    }

    //返回过滤器的执行顺序的值，值越小就先执行
    public int filterOrder() {
        return 0;
    }

    //返回一个boolean类型判断过滤器是否要执行，true执行 false不执行
    public boolean shouldFilter() {
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        Cookie[] cookies = request.getCookies();
        if(cookies == null || cookies.length == 0){
            shouldNotFilter(context);
            return null;
        }else{
            context.setSendZuulResponse(true);
            context.setResponseStatusCode(200);
            context.set("isSuccess",true);
        }
        return null;
    }

    public void shouldNotFilter(RequestContext context) {
        context.setSendZuulResponse(false);
        context.setResponseStatusCode(401);
        context.setResponseBody("权限不够");
        context.set("isSuccess",false);
    }
}
